
package cn.jekun.web.shop.action;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.exceptions.TimeoutException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsAuth;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.web.shop.bean.UserLogin;
import cn.jekun.web.shop.bean.UserShops;
import cn.jekun.web.shop.bean.WebUser;
import cn.jekun.web.shop.service.LoginService;

/**
 * 商家登录、退出系统 
 * @author yuan
 *
 */
@SuppressWarnings("serial")
public class LoginAction extends ShopBaseAction {

	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService userService;
	
	@Resource(name=LoginService.BEAN_NAME)
	LoginService loginService;

	private String userName;
	private String password;
	private String loginCount;
	private String shopId;
	private String logintype;
	public String getLogintype() {
		return logintype;
	}

	public void setLogintype(String logintype) {
		this.logintype = logintype;
	}

	public String getShopId() {
		return shopId;
	}

	public void setShopId(String shopId) {
		this.shopId = shopId;
	}

	public String getLoginCount() {
		return loginCount;
	}

	public void setLoginCount(String loginCount) {
		this.loginCount = loginCount;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	protected void validateTimeout() throws TimeoutException {
		//不需要登录
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String Login(){
//        if(userName==null || password ==null){
//			return "/login.jsp";
//        }
//		WebUser webUser = new WebUser();
//		//查找用户
//		formMap.put(RsUser.COL_USER_NAME, userName);
//		SqlUtis.prepareSql(formMap
//				, SqlUtis.getSQL(formMap,"a."+RsUser.COL_USER_NAME,Types.VARCHAR,SqlUtis.EQ)
//				);
//		RsUser user = this.userService.one(this.formMap);
//		if (user==null) {//手机号码
//			formMap.put(RsUser.COL_MOBILE, userName);
//			SqlUtis.prepareSql(formMap
//					, SqlUtis.getSQL(formMap,"a."+RsUser.COL_MOBILE,Types.VARCHAR,SqlUtis.EQ)
//					);
//			user = this.userService.one(this.formMap);
//		}
//		if(user==null){
//			this.saveActionError("用户名或密码不正确");
//			return "/login.jsp";
//		}
//		//检查密码
//		if(!password.equals(user.getPassword())){
//			this.saveActionError("用户名或密码不正确");
//			return "/login.jsp";
//		}
//		Map map = new HashMap();
//		map.put("userName", userName);
//		map.put("userId", user.getUserId());
//		//TODO 检查用户是否有商家及商家分店列表
//		List<UserShops> list = this.userService.list("ACTION_RS_USER_LOGIN.list", map);
//		UserLogin userLogin = this.loginService.one("ACTION_RS_USER_LOGIN.queryshoplogin",map);
//
//		if(list==null || list.isEmpty()){
//			this.saveActionError("没有任何商家信息");
//			return "/login.jsp";
//		}else{
//			//将登录用户的相关信息保存于webUser;
//			webUser.setUserId(user.getUserId());
//			webUser.setRealName(user.getRealName());
//			webUser.setMobile(user.getMobile());
//			webUser.setUserName(user.getUserName());
//			webUser.setIp(getIp(request));
//			webUser.setBrowser(getBrowser(request));
//			webUser.setLogintype(logintype);
//			webUser.setShopId(list.get(0).getShopId()); //当前商家Id
//			webUser.setShopName(list.get(0).getShopName()); //当前商家Name
//			webUser.setShopMobile(list.get(0).getShopMobile());
//			webUser.setShopLogoUrl(list.get(0).getLogoUrl());//商家图标
//			webUser.setLoginlogs(userLogin==null?null:userLogin);
//			webUser.setShopSize(list.size());
//			if(list.size()>1)list.remove(0);
//			webUser.setUserShops(list); //所有商家列表(分店)
//		}
//		//保存于session
//		this.request.getSession().setAttribute(WebUser.SESSION_KEY, webUser);
//		//查找用户的菜单
//		List<RsAuth> menus = null;
//		if (this.coreAuthService.isAdmin(this.getSessionUser().getUserId())) {//超级管理员
//			menus = this.coreAuthService.list(this.coreAuthService.getStatementName("selectAllMenu"),null);//所有菜单
//		} else {
//			menus = this.coreAuthService.list(this.coreAuthService.getStatementName("selectMenu"),null);//用户可以看到的所有菜单
//		}
//		webUser.setMenus(menus);
//
//		return "!/shop/main.jsp";
		
		
		JSONObject jsonObject=new JSONObject();
		
		
		WebUser webUser = new WebUser();
		RsUser user = this.loginService.one(userName);
		if(user==null){
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "用户不存在");
			
			return this.writeJson(jsonObject);
		}

		//检查密码
		if(!password.equals(user.getPassword())){
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "用户名或密码不正确");
			
			return this.writeJson(jsonObject);
		}
		Map map = new HashMap();
		map.put("userName", userName);
		map.put("userId", user.getUserId());
		//TODO 检查用户是否有商家及商家分店列表
		List<UserShops> list = this.userService.list("ACTION_RS_USER_LOGIN.list", map);
		UserLogin userLogin = this.loginService.one("ACTION_RS_USER_LOGIN.queryshoplogin",map);

		if(list==null || list.isEmpty()){
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"该用户不是商家店员");
			
			return this.writeJson(jsonObject);
		}else{
			//将登录用户的相关信息保存于webUser;
			webUser.setUserId(user.getUserId());
			webUser.setRealName(user.getRealName());
			webUser.setMobile(user.getMobile());
			webUser.setUserName(user.getUserName());
			webUser.setIp(this.getIp());
			webUser.setBrowser(this.getBrowser());
			webUser.setLogintype(logintype);
			webUser.setShopId(list.get(0).getShopId()); //当前商家Id
			webUser.setShopName(list.get(0).getShopName()); //当前商家Name
			webUser.setShopMobile(list.get(0).getShopMobile());
			webUser.setShopLogoUrl(list.get(0).getLogoUrl());//商家图标
			webUser.setLoginlogs(userLogin==null?null:userLogin);
			webUser.setShopSize(list.size());
			if(list.size()>1)list.remove(0);
			webUser.setUserShops(list); //所有商家列表(分店)
		}
		//保存于session
		this.request.getSession().setAttribute(WebUser.SESSION_KEY, webUser);
		//查找用户的菜单
		List<RsAuth> menus = null;
		if (this.coreAuthService.isAdmin(this.getSessionUser().getUserId())) {//超级管理员
			menus = this.coreAuthService.getAllMenus(Constants.RS_SYSTEM.SHOP);//所有菜单
		} else {
			menus = this.coreAuthService.getMenus(Constants.RS_SYSTEM.SHOP, user.getUserId());//用户可以看到的所有菜单
		}
		webUser.setMenus(menus);
		
		JSONArray jsonArray = new JSONArray();
	
		HashMap<String, Object> hashMap=new HashMap<String, Object>();
		
		for(int i=0;i<menus.size();i++){
			
		
			hashMap.put(RsAuth.COL_AUTH_NAME, menus.get(i).getAuthName());
			
			hashMap.put(RsAuth.COL_PARENT_ID, menus.get(i).getParentId());
			
			hashMap.put(RsAuth.COL_AUTH_ID, menus.get(i).getAuthId());
			
			hashMap.put(RsAuth.COL_URL, menus.get(i).getUrl());
			
			jsonArray.add(hashMap);
			
		}
		
		
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		
		jsonObject.put("menusData", jsonArray);
		
		return this.writeJson(jsonObject);
		
	}

	/**
	 * 退出系统
	 * @return
	 */
	public String loginOut(){
		request.getSession().removeAttribute(WebUser.SESSION_KEY);
		request.getSession().invalidate();
		return "!/v1/pages/index.jsp";	
	}
	/**
	 * 切换商家分店
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getChangeShops(){
		Map map = new HashMap();
		map.put("userName", this.getSessionUser().getUserName());
		map.put("userId",this.getSessionUser().getUserId());
		List<UserShops> shopList =userService.list("ACTION_RS_USER_LOGIN.list", map);
		UserLogin userLogin = this.loginService.one("ACTION_RS_USER_LOGIN.queryshoplogin",map);
		this.getSessionUser().setShopId(shopId);
		this.getSessionUser().setLoginlogs(userLogin==null?null:userLogin);
		for(int i=0;i<shopList.size();i++){
			if(shopId.equals(shopList.get(i).getShopId())){
				this.getSessionUser().setShopName(shopList.get(i).getShopName());
				shopList.remove(i);
			}
		}
		this.getSessionUser().setUserShops(shopList);
		return "!/shop/main.jsp";
	}
	
	/**
     * 在首頁顯示的圖標的權限
     * @return
     */
	public String queryShowOperate(){
	    JSONObject jsonObject = new JSONObject();
		try{
			boolean SHOP_ORDER_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_ORDER_MANAGER"); //订单查询
			boolean SHOP_TERNIMAL_MONITOR_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_TERNIMAL_MONITOR_MANAGER"); //设备监控
			boolean SHOP_TERNIMAL_USER_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_TERNIMAL_USER_MANAGER"); //操作员查询
			boolean SHOP_MY_BANK_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_BANK_MANAGER"); //银行账户
			boolean SHOP_MY_INFO_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_INFO_MANAGER"); //基本信息
			boolean SHOP_MY_SECURITY_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_SECURITY_MANAGER"); //安全设置
			boolean SHOP_MY_ACCOUNT_SETTLE_HIS_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_ACCOUNT_SETTLE_HIS_MANAGER"); //提现记录
			boolean SHOP_MY_ACCOUNT_SETTLE_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_ACCOUNT_SETTLE_MANAGER"); //提现
			boolean SHOP_MY_ACCOUNT_JOURNAL_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MY_ACCOUNT_JOURNAL_MANAGER"); //账户流水
			boolean SHOP_MC_MEMBER_SEARCH_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_MC_MEMBER_SEARCH_MANAGER"); //账户流水
			boolean SHOP_GOODS_MANAGER=this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_GOODS_MANAGER"); //账户流水

			jsonObject.put("SHOP_ORDER_MANAGER", SHOP_ORDER_MANAGER);
			jsonObject.put("SHOP_TERNIMAL_MONITOR_MANAGER", SHOP_TERNIMAL_MONITOR_MANAGER);
			jsonObject.put("SHOP_TERNIMAL_USER_MANAGER", SHOP_TERNIMAL_USER_MANAGER);
			jsonObject.put("SHOP_MY_BANK_MANAGER", SHOP_MY_BANK_MANAGER);
			jsonObject.put("SHOP_MY_INFO_MANAGER", SHOP_MY_INFO_MANAGER);
			jsonObject.put("SHOP_MY_SECURITY_MANAGER", SHOP_MY_SECURITY_MANAGER);
			jsonObject.put("SHOP_MY_ACCOUNT_SETTLE_HIS_MANAGER",SHOP_MY_ACCOUNT_SETTLE_HIS_MANAGER);
			jsonObject.put("SHOP_MY_ACCOUNT_SETTLE_MANAGER", SHOP_MY_ACCOUNT_SETTLE_MANAGER);
			jsonObject.put("SHOP_MY_ACCOUNT_JOURNAL_MANAGER", SHOP_MY_ACCOUNT_JOURNAL_MANAGER);
			jsonObject.put("SHOP_MC_MEMBER_SEARCH_MANAGER", SHOP_MC_MEMBER_SEARCH_MANAGER);
			jsonObject.put("SHOP_GOODS_MANAGER", SHOP_GOODS_MANAGER);
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		}catch(BusinessException e){
   	       		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
   	       		jsonObject.put(ErrorMsg.KEY_MESSAGE, e.getMessage());
		}catch(Exception e){
	       		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
	       		jsonObject.put(ErrorMsg.KEY_MESSAGE, e.getMessage());
		}
		System.out.println("jsonObject="+jsonObject);
  		return this.writeJson(jsonObject);
	}
	
	/**
	 * 查询用户菜单
	 * @return
	 */
	public String queryUserMenus(){
		
		JSONObject jsonObject=new JSONObject();
		String systemId=Constants.RS_SYSTEM.SHOP;
		try {
			//查找用户的菜单
			List<RsAuth> menus = null;
			if (this.coreAuthService.isAdmin(this.getSessionUser().getUserId())) {//超级管理员
//				menus = this.coreAuthService.list(this.coreAuthService.getStatementName("selectAllMenu"),null);//所有菜单
				menus = this.coreAuthService.getAllMenus(Constants.RS_SYSTEM.SHOP);//所有菜单

				
			} else {
				
//				menus = this.coreAuthService.list(this.coreAuthService.getStatementName("selectMenu"),null);//用户可以看到的所有菜单
				menus = this.coreAuthService.getMenus(Constants.RS_SYSTEM.SHOP, this.getSessionUser().getUserId());//用户可以看到的所有菜单

			}
			JSONArray jsonArray = new JSONArray();
		
			HashMap<String, Object> hashMap;
			
			for(int i=0;i<menus.size();i++){
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put(RsAuth.COL_AUTH_NAME, menus.get(i).getAuthName());
				
				hashMap.put(RsAuth.COL_PARENT_ID, menus.get(i).getParentId()==null?"":menus.get(i).getParentId());
				
				hashMap.put(RsAuth.COL_AUTH_ID, menus.get(i).getAuthId());
				
				hashMap.put(RsAuth.COL_URL, menus.get(i).getUrl());
				
				hashMap.put(RsAuth.COL_MEMO, menus.get(i).getMemo());
				
				jsonArray.add(hashMap);
				
			}
					
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
			jsonObject.put("menusData", jsonArray);
			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		return this.writeJson(jsonObject);
	}
	
/**
 * 验证手机和登录名是否绑定
 * @return
 */
public String checkBindingMobile(){
	JSONObject jsonObject=new JSONObject();
	String userName=request.getParameter("userName");
	String mobile=request.getParameter("mobile");
	
	try {
		String userId=this.loginService.getUserIdByMobile(userName,mobile);
		jsonObject.put("userId", userId);
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
	}catch(BusinessException e){
      		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
      		jsonObject.put(ErrorMsg.KEY_MESSAGE, e.getMessage());
	}catch(Exception e){
   		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
   		jsonObject.put(ErrorMsg.KEY_MESSAGE, e.getMessage());
	}
	return this.writeJson(jsonObject);
		
}

/**
 * 修改登录密码
 * @return
 */
public String resetPassword(){
	
	JSONObject jsonObject=new JSONObject();
	String userId=request.getParameter("userId");
	String newPwd=request.getParameter("newPwd");
	
	try {
		// 检查是否存在用户
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, SqlUtis.getSQLRequired(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
		boolean exists = this.userService.exists(formMap);
		if (!exists) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"用户不存在！");
			return this.writeJson(jsonObject);
		}
		RsUser user = this.userService.one(formMap);
		
		user.setPassword(newPwd);
		formMap.put("rsUser", user);
		this.userService.update(formMap);
		
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"重置登录密码成功!");
		
		
	} catch (BusinessException e) {
		jsonObject = JSONObject.fromObject(e.getErrorMsg());
	} catch (Exception e) {
		jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		e.printStackTrace();
	}
	return this.writeJson(jsonObject);
}
	
	/**
	 * 找回登录密码
	 * 发送手机验证码
	 * @return
	 */
	public String sendValidateCode(){

		JSONObject jsonObject = null;

		try {
			jsonObject = loginService.sendValidateCode(request.getParameter("mobile"));
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
	
	/**
	 * 校验验证码是否正确
	 * @return
	 */
	public String  getValidateCode(){
	  
		JSONObject jsonObject = null;

		try {
			jsonObject = loginService.checkValidateCode(request.getParameter("mobile")
					,request.getParameter("validatecode"));
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 验证登录是否超时
	 */
	public String isLoginTimeOut(){
		
		JSONObject jsonObject=new JSONObject();
		System.out.println("验证登录是否超时");
		try{
			
			if(!isLoginWeb()){
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"登录超时");
				
			}else{
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"有效");
			}
	
				
		}catch(Exception e){
			
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"登录超时");
		}
		
		return this.writeJson(jsonObject);
		
	}
	
}
